<template>
  <div class="students-container">
    <div class="actionBtn flex justifyBetween alignCenter" ref="actionBtnRef">
      <!-- v-if="counter.isShowActionBtn(props.info)" -->
      <div>
        <el-button
          type="primary"
          @click="proxy.$refs.addClassStudentsRef.open(props.info)"
          >新增学员</el-button
        >
        <!-- <el-button type="primary" plain @click="handleClick(7)">团体导入</el-button> -->
        <el-button
          :disabled="!selectArr.length"
          type="danger"
          plain
          @click="handleClick(3)"
          >移出本班</el-button
        >
        <el-button :disabled="!selectArr.length" plain @click="handleClick(2)"
          >调至其他班</el-button
        >
        <el-button :disabled="!selectArr.length" plain @click="handleClick(1)"
          >修改学员状态</el-button
        >
        <el-button :disabled="!selectArr.length" plain @click="handleClick(9)"
          >报名所属</el-button
        >
        <el-dropdown style="margin-left: 10px">
          <el-button plain>更多操作</el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                @click="handleClick(4)"
                :disabled="!selectArr.length"
                >导出学员信息</el-dropdown-item
              >
              <el-dropdown-item
                @click="handleClick(12)"
                :disabled="!selectArr.length"
                >导出学员附件</el-dropdown-item
              >
              <el-dropdown-item
                @click="handleClick(10)"
                :disabled="!selectArr.length"
                >设置课程标签</el-dropdown-item
              >
              <el-dropdown-item
                @click="handleClick(11, '0')"
                :disabled="!selectArr.length"
                >开启线上账号</el-dropdown-item
              >
              <el-dropdown-item
                @click="handleClick(11, '1')"
                :disabled="!selectArr.length"
                >关闭线上账号</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <!-- <el-button type="primary" plain @click="handleClick(8)">添加历史学员</el-button> -->
      </div>
      <span class="flex alignCenter">
        <el-dropdown style="cursor: pointer">
          <span class="el-dropdown-link flex alignCenter">
            <el-icon>
              <Sort />
            </el-icon>
            <div class="shrink">
              {{
                sortArr[
                  proxy.$utils.findIndexByField(
                    sortArr,
                    "value",
                    formInline.sort
                  )
                ].name
              }}
            </div>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item
                @click="setSort(item.value)"
                v-for="(item, index) in sortArr"
                :key="index"
                >{{ item.name }}</el-dropdown-item
              >
            </el-dropdown-menu>
          </template>
        </el-dropdown>

        <div style="margin-left: 15px">
          <el-input
            v-model="formInline.keyWords"
            @clear="search"
            @change="search"
            clearable
            placeholder="搜索学员姓名/联系方式"
          >
            <template #append>
              <el-button icon="Search" @click="search" />
            </template>
          </el-input>
        </div>
      </span>
    </div>

    <el-table
      :max-height="tableMaxHeight"
      :row-class-name="tableRowClassName"
      ref="multipleTableRef"
      v-loading="loading"
      :data="tableParams.rows"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column label="状态" prop="name" width="55" fixed="left">
        <template #default="scope">
          <el-tooltip
            class="box-item"
            v-if="scope.row.userState == 0"
            effect="dark"
            :content="`停课日期 ${scope.row.suspensionClassDate}`"
            placement="top"
          >
            <div style="color: #8530f5">停课</div>
          </el-tooltip>
          <div class="status-icon" v-else-if="scope.row.userState == 2">
            <img
              src="https://shdiditazi.oss-cn-shanghai.aliyuncs.com/image/6ec5b77ded30e5ff51a211dd703a097f.png"
              alt=""
            />
          </div>
          <div v-else class="status-icon">
            <img src="@/assets/images/checkIcon.png" alt="" />
          </div>
        </template>
      </el-table-column>
      <el-table-column type="index" width="50" label="序号" fixed="left">
        <template #default="scope">
          {{
            (formInline.pageIndex - 1) * formInline.pageSize + scope.$index + 1
          }}
        </template>
      </el-table-column>
      <el-table-column label="姓名" width="70" fixed="left">
        <template #default="scope">
          {{ field_format(scope.row, "name") }}
        </template>
      </el-table-column>
      <el-table-column label="联系方式" width="110" fixed="left">
        <template #default="scope">
          {{ field_format(scope.row, "mobile") }}
        </template>
      </el-table-column>
      <el-table-column
        label="报名所属"
        width="120"
        prop="affiliation_dictLabel"
        show-overflow-tooltip
      >
        <template #default="scope">
          {{ scope.row.affiliation_dictLabel || affiliation_format(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="性别" prop="name" width="55">
        <template #default="scope">
          {{ getGenderByIdCard(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column label="身份证号" width="165">
        <template #default="scope">
          {{ field_format(scope.row, "identityCard") }}
        </template>
      </el-table-column>
      <el-table-column label="所在企业名称" width="200" show-overflow-tooltip>
        <template #default="scope">
          {{ field_format(scope.row, "enterprise") }}
        </template>
      </el-table-column>
      <el-table-column label="就业状态" width="80" show-overflow-tooltip>
        <template #default="scope">
          {{ field_format(scope.row, "employed_Status") }}
        </template>
      </el-table-column>
      <el-table-column label="累计工作年限" width="110" show-overflow-tooltip>
        <template #default="scope">
          {{ field_format(scope.row, "workYears") }}
        </template>
      </el-table-column>
      <el-table-column label="最高学历" width="165" show-overflow-tooltip>
        <template #default="scope">
          {{ field_format(scope.row, "education") }}
        </template>
      </el-table-column>
      <el-table-column label="毕业专业" width="180" show-overflow-tooltip>
        <template #default="scope">
          {{ field_format(scope.row, "graduationMajor") }}
        </template>
      </el-table-column>
      <el-table-column label="毕业院校" width="180" show-overflow-tooltip>
        <template #default="scope">
          {{ field_format(scope.row, "school") }}
        </template>
      </el-table-column>
      <el-table-column prop="order_Info.price" label="订单金额" width="85">
        <template #default="scope">
          <div class="flex alignCenter">
            {{ proxy.$utils.formatNumber(scope.row.order_Info.displayPrice) }}
            <div
              class="minus classStatus"
              v-if="scope.row.order_Info.status == 10"
            >
              减
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="报名状态" width="120" align="center">
        <template #default="scope">
          <div v-if="scope.row.order_Info.status">
            <el-tag
              type="danger"
              v-if="
                scope.row.order_Info.status == 1 &&
                scope.row.order_Info.rejectMsg
              "
              >已驳回</el-tag
            >
            <el-tag
              v-else
              :color="counter.tagBgColor(scope.row.order_Info.status)"
            >
              <div
                :style="{
                  color: counter.tagColor(scope.row.order_Info.status),
                }"
              >
                {{ status_format(scope.row.order_Info.status) }}
              </div>
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="进班日期" align="center" width="100">
        <template #default="scope">
          {{ proxy.$utils.dateTimeFormateFn(scope.row._add_time) }}
        </template>
      </el-table-column>
      <el-table-column prop="name" label="人社刷卡" fixed="right" width="100">
        <template #default="scope">
          <el-switch
            @change="handleSubmit(scope.row)"
            v-model="scope.row.isSubmit"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        prop="address"
        label="备注"
        min-width="150"
        fixed="right"
      >
        <template #default="scope">
          <el-input
            @change="remarkChange(scope.row, 'remark')"
            v-model="scope.row.remark"
            placeholder="请输入备注"
          />
        </template>
      </el-table-column>
    </el-table>

    <pagination
      :selectNum="selectArr.length"
      v-if="tableParams['total']"
      :total="tableParams['total']"
      v-model:page="formInline.pageIndex"
      v-model:limit="formInline.pageSize"
      @pagination="getInfo"
      :totalPrice="total"
    />

    <!-- 新增学员 -->
    <addClassStudents
      ref="addClassStudentsRef"
      @fatherMethod="search"
    ></addClassStudents>

    <!-- 批量操作 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTips"
      width="500"
      :before-close="handleClose"
    >
      <div v-if="visibleNum == 1">
        <el-select v-model="userState" placeholder="请选择">
          <el-option label="正常" :value="1" />
          <el-option label="停课" :value="0" />
          <el-option label="延期考试" :value="2" />
        </el-select>
        <!-- 停课日期 -->
        <div style="margin-top: 15px">
          <DatePicker
            placeholder="请选择停课日期"
            v-model="suspensionClassDate"
            v-if="userState == 0"
          ></DatePicker>
        </div>
      </div>
      <el-select
        filterable
        v-model="otherClassId"
        placeholder="请选择班级名称"
        v-else-if="visibleNum == 2"
      >
        <el-option
          :label="item.className"
          :value="item._id"
          v-for="(item, index) in otherClassOptions"
          :key="index"
        >
          <el-row :gutter="20">
            <el-col :span="20">
              <div>{{ item.className }}</div>
            </el-col>
            <el-col :span="2">
              <div v-if="item.status == 0" style="color: #e99d42">待开班</div>
              <div v-else-if="item.status == 1" style="color: #54c076">
                开班
              </div>
              <div v-else>结业</div>
            </el-col>
            <el-col :span="2">
              <div>{{ item.classStudentsNum }}/{{ item.classNum }}</div>
            </el-col>
          </el-row>
        </el-option>
      </el-select>
      <el-input
        v-model="declarationBatchNumber"
        v-else-if="visibleNum == 5"
        placeholder="请输入申请批次号"
      />

      <!-- 报名所属 -->
      <dictSelect
        v-model="affiliation"
        v-else-if="visibleNum == 9"
        dictCode="registration_affiliation"
      ></dictSelect>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submit" :loading="loading">
            确 认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 线下学员导入 -->
    <input
      type="file"
      @change="handleStudentFileImport"
      v-show="false"
      ref="studentFileClick"
    />

    <!-- 历史学员导入 -->
    <historyStudents
      ref="historyStudentsRef"
      :classInfo="props.info"
      @fatherMethods="search"
    ></historyStudents>

    <!-- 设置魔学院 -->
    <editMoxueyuan
      ref="editMoxueyuanRef"
      @fatherMethod="getInfo"
    ></editMoxueyuan>
  </div>
</template>

<script setup lang="ts">
//设置魔学院
import editMoxueyuan from "@/views/order/components/editMoxueyuan.vue";
import historyStudents from "@/views/courseManage/components/historyStudents.vue";
import addClassStudents from "@/views/courseManage/components/addClassStudents.vue";
const { proxy } = getCurrentInstance();
import useCounterStore from "@/store/counter";
import { onMounted } from "vue";
const counter = useCounterStore();
let props = defineProps(["info"]);

let dialogVisible = ref(false);
let visibleNum = ref(null);
let userState = ref(1); //学员状态
let affiliation = ref([]); //报名所属
let suspensionClassDate = ref(null); //停课日期
let declarationBatchNumber = ref(null); //申报批次号
let isExamination = ref(1); //考试鉴定
let otherClassOptions = ref([]); //调班班级
let formInline = ref({
  pageIndex: 1,
  pageSize: 500,
  classId: "",
  keyWords: "",
  sort: "userPinyin",
});
let otherClassId = ref(null); //其他班级
let selectArr = ref([]);
let tableParams = ref({});
let tabs = ref([
  { name: "待审核", value: 1 },
  { name: "审核未通过", value: 3 },
  { name: "支付尾款", value: 8 },
  { name: "报名成功", value: 2 },
  { name: "优惠减免", value: 10 },
  { name: "已退款", value: 4 },
  { name: "部分退款", value: 9 },
  { name: "已开票", value: 7 },
]);
let sortArr = ref([
  { name: "按姓名默认排序", value: "userPinyin" },
  { name: "按报名所属排序", value: "affiliationPinyin" },
  { name: "按所在企业名称排序", value: "enterprisePinyin" },
]);
let loading = ref(false);

let actionBtnHeight = ref(0);
let selectedRow = ref([]);

let dialogTips = computed(() => {
  switch (visibleNum.value) {
    case 1:
      return "修改学员状态";
      break;
    case 2:
      return "调至其他班";
      break;
    case 5:
      return "学员申报";
      break;
    case 9:
      return "报名所属";
      break;
    default:
      break;
  }
});

let tableMaxHeight = computed(() => {
  let hei =
    window.innerHeight -
    84 -
    counter.pageHeight -
    110 -
    actionBtnHeight.value -
    counter.classCardHeight;
  return `${hei}px`;
});

let total = computed(() => {
  let num = 0;
  tableParams.value.rows.forEach((element) => {
    num += element.order_Info.displayPrice;
  });
  return num;
});

onMounted(() => {
  actionBtnHeight.value = proxy.$refs.actionBtnRef.offsetHeight;
  counter.getAffiliation();
  console.log("actionBtnHeight", actionBtnHeight.value);
});

function setSort(value) {
  formInline.value.sort = value;
  search();
}

//是否报送人设
function handleSubmit(data) {
  remarkChange(data, "isSubmit");
}

function search() {
  formInline.value.pageIndex = 1;
  getInfo();
}

const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: User;
  rowIndex: number;
}) => {
  if (row.source && row.source == "file") {
    return "warning-row";
  }
  return "";
};

function field_format(item, key) {
  let row = item.source ? item.user_data : item.order_Info.orderUserInfo;
  if (key == "enterprise") return counter.showEnterprise(row, key);
  return row[key];
}

function affiliation_format(row) {
  if (!row.affiliation) return "-";
  let key;
  let list = counter.dictOptions["registration_affiliation"] || [];
  if (proxy.$utils.isString(row.affiliation)) {
    key = row.affiliation;
  } else if (proxy.$utils.isJsonArray(row.affiliation) == "arr") {
    key = row.affiliation[0];
  }
  let current = proxy.$utils.findIndexByField(list, "dict_code", key);
  if (current != -1) return list[current].dict_label;
  return "-";
}

function getGenderByIdCard(item) {
  let row = item.source ? item.user_data : item.order_Info.orderUserInfo;
  let idCard = row.identityCard;
  if (!idCard || idCard.length !== 18) return "-";
  const sexCode = idCard.charAt(16);
  const gender = parseInt(sexCode, 10) % 2 === 0 ? "女" : "男";
  return gender;
}

async function handleStudentFileImport(event) {
  try {
    const files = event.target.files;

    //return counter.importTemplate(files, "offline-student-template");

    let file = files[0];
    let resp = await proxy.$utils.fileToJson(file);
    console.log("导入信息解析", resp);
    let list = [];
    for (let index = 0; index < resp.length; index++) {
      const element = resp[index];
      if (index) {
        list.push({
          name: element[0],
          mobile: element[1],
          gender: element[2],
          identityCard: element[3],
          enterprise: element[4],
          education: element[5],
        });
      }
    }
    await proxy.$apis.classStudent({
      type: "offline-student-import",
      data: { list, classId: props.info._id },
    });
    proxy.$utils.showToast("导入成功");
    getInfo();
  } catch (error) {
  } finally {
    event.target.value = "";
  }
}

async function otherClass() {
  let resp = await proxy.$apis.classStudent({
    type: "otherClass",
    data: {
      classId: props.info._id,
      curriculumId: props.info.curriculumId,
    },
  });
  for (let index = 0; index < resp.length; index++) {
    const element = resp[index];
    //班级人数
    let classStudentsList = await proxy.$apis.classStudent({
      type: "query",
      data: { classId: element._id },
    });
    element.classStudentsNum = classStudentsList.length;
  }
  otherClassOptions.value = resp;
}

async function submit() {
  try {
    loading.value = true;
    if (visibleNum.value == 2) {
      let resp = await proxy.$utils.confirmTips("确认对选中的学员调班?");
      if (!resp) return;
    } else if (visibleNum.value == 1) {
      //修改学员状态
      if (userState.value == 0 && !suspensionClassDate.value) {
        return proxy.$utils.showToast("请选择停课日期", 0);
      }
    } else if (visibleNum.value == 9) {
      if (!affiliation.value.length)
        return proxy.$utils.showToast("请选择报名所属", 0);
    }
    for (let index = 0; index < selectArr.value.length; index++) {
      const element = selectArr.value[index];
      let data = { _id: element };
      switch (visibleNum.value) {
        case 1:
          data["userState"] = userState.value;
          data["suspensionClassDate"] = suspensionClassDate.value; //停课日期
          break;
        case 2:
          data["classId"] = otherClassId.value;
          break;
        case 5:
          data["declarationBatchNumber"] = declarationBatchNumber.value;
          break;
        case 9:
          data["affiliation"] = affiliation.value;
          data["affiliation_dictLabel"] = affiliation_format({
            affiliation: affiliation.value,
          });
          break;
        default:
          break;
      }
      await proxy.$apis.classStudent({
        type: "update",
        data,
      });
    }
    proxy.$utils.showToast("操作成功");
    handleClose();
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

function handleSelectionChange(e) {
  selectArr.value = [];
  selectedRow.value = e;
  e.forEach((element) => {
    selectArr.value.push(element._id);
  });
}

function handleClose() {
  userState.value = 1;
  suspensionClassDate.value = null;
  isExamination.value = 1;
  declarationBatchNumber.value = null;
  selectArr.value = [];
  otherClassId.value = null;
  affiliation.value = [];
  getInfo();
  dialogVisible.value = false;
}

function status_format(e) {
  if (e == 8) {
    return "支付尾款";
  } else if (e == 10) {
    return "报名成功";
  } else {
    for (let index = 0; index < tabs.value.length; index++) {
      const element = tabs.value[index];
      if (element.value == e) return element.name;
    }
  }
}

async function handleClick(num, type?) {
  try {
    visibleNum.value = num;
    switch (num) {
      case 1:
        dialogVisible.value = true;
        break;
      case 2:
        await proxy.$apis.classStudent({
          type: "canMoveOtherClass",
          data: selectArr.value,
        });
        dialogVisible.value = true;
        break;
      case 3:
        let resp = await proxy.$utils.confirmTips("确认移出本班?");
        if (!resp) return;
        for (let index = 0; index < selectArr.value.length; index++) {
          const element = selectArr.value[index];
          let current = proxy.$utils.findIndexByField(
            tableParams.value.rows,
            "_id",
            element
          );
          //线下学员同步删除
          if (current != -1) {
            let item = tableParams.value.rows[current];
            if (item.offlineUserId) {
              await proxy.$apis.classStudent({
                type: "del-offline-student",
                data: { offlineUserId: item.offlineUserId },
              });
            }
          }
          await proxy.$apis.classStudent({
            type: "del",
            data: { _id: element },
          });
        }
        proxy.$utils.showToast("移出成功");
        getInfo();
        break;
      case 4: //导出学员
        exportStudents();
        break;
      case 5:
        dialogVisible.value = true;
        break;
      case 6:
        //下载模板
        counter.downLoadTemplate("class-student-achievement", "成绩导入模板");
        proxy.$refs.fileClick.click();
        break;
      case 7: //线下学员
        proxy.$refs.studentFileClick.click();
        counter.downLoadTemplate("offline-student-template", "团体导入模板");
        break;
      case 8: //历史学员导入
        proxy.$refs.historyStudentsRef.open();
        break;
      case 9: //报名所属
        dialogVisible.value = true;
        break;
      case 10: //设置课程标签
        proxy.$refs.editMoxueyuanRef.open(selectedRow.value);
        break;
      case 11: //设置魔学院账号状态
        let result = await proxy.$utils.confirmTips(
          "确定要批量" + (type == "0" ? "开启" : "关闭") + "所选账号吗?"
        );
        if (!result) return;
        for (let index = 0; index < selectedRow.value.length; index++) {
          const element = selectedRow.value[index];
          let data = { mobile: element.order_Info.mobile, disabled: type };
          await proxy.$apis.moxueyuanInfo({ type: "update", data });
        }
        proxy.$utils.showToast("操作成功");
        break;
      case 12: //导出学员附件
        let arr = [];
        selectedRow.value.forEach((element) => {
          arr.push(element.orderId);
        });
        counter.exportAttachment(arr);
        break;
      default:
        break;
    }
  } catch (error) {
    console.log("学员操作报错", error);
  }
}

//导出学员
async function exportStudents() {
  let rows = selectedRow.value;
  let data = [];
  let cols = []; //设置表头样式
  rows.forEach((element, index) => {
    cols.push({ wch: 20 });
    data.push({
      序号: index + 1,
      状态: element.userState == 0 ? "停课" : "正常",
      姓名: field_format(element, "name"),
      联系方式: field_format(element, "mobile"),
      报名所属: element.affiliation_dictLabel,
      性别: getGenderByIdCard(element),
      身份证号: field_format(element, "identityCard"),
      所在企业名称: field_format(element, "enterprise"),
      就业状态: field_format(element, "employed_Status"),
      累计工作年限: field_format(element, "workYears"),
      最高学历: field_format(element, "education"),
      毕业专业: field_format(element, "graduationMajor"),
      毕业院校: field_format(element, "school"),
      订单金额: proxy.$utils.formatNumber(element.order_Info.displayPrice),
      报名状态: status_format(element.order_Info.status),
      备注: element.remark,
      证书编号: element.certificateNumber,
      申请批次号: element.declarationBatchNumber,
      理论: element.theory,
      实训: element.practicalTraining,
      获证情况: certificationStatus(element),
      进班日期: proxy.$utils.dateTimeFormateFn(element._add_time),
    });
  });
  let query = { jsonData: data, cols };
  await proxy.$utils.exportToExcel(query, "班级学员信息");
}

function certificationStatus(e) {
  if (!e.hasOwnProperty("isExamination")) return "-";
  if (e.isExamination == 0) {
    return "未获证";
  } else if (e.isExamination == 1) {
    return "获证";
  } else if (e.isExamination == 2) {
    return "未出考";
  }
}

async function remarkChange(e, key) {
  let obj = { _id: e._id };
  obj[key] = e[key];
  await proxy.$apis.classStudent({
    type: "update",
    data: obj,
  });
  proxy.$utils.showToast("修改成功");
  getInfo();
}

async function getInfo() {
  try {
    loading.value = true;
    if (!props.info._id) return;
    formInline.value.classId = props.info._id;
    formInline.value.keyWords = formInline.value.keyWords.trim();
    tableParams.value = await proxy.$apis.classStudent({
      type: "list",
      data: formInline.value,
    });
    console.log("tableParams.value", tableParams.value);
  } catch (error) {
  } finally {
    loading.value = false;
  }
}

watch(
  () => props.info,
  (newValue, oldValue) => {
    if (newValue) {
      search();
      otherClass();
    }
  },
  { immediate: true, deep: true }
);
</script>

<style lang="scss" scoped>
.actionBtn {
  margin-bottom: 15px;
}
.el-tag {
  border-color: transparent;
}
.status-icon {
  width: 15px;
  height: 15px;
  img {
    width: 100%;
    display: block;
  }
}
.extendedExam {
  color: #e6a23c;
}
.classStatus {
  border-radius: 50%;
  margin-left: 5px;
  width: 18px;
  height: 18px;
  line-height: 18px;
  text-align: center;
  color: #97999e;
  border: 1px solid #97999e;
  cursor: pointer;
  font-size: 12px;
  font-weight: bold;
}
.minus {
  color: #f66604 !important;
  border: 1px solid #f66604 !important;
}
</style>
